/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Control.Control;
import DataBase.GlobalException;
import DataBase.NoDataException;
import DataBase.ServicioMenu;
import Logic.Filtro;
import Logic.Log;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author David-PC
 */
public class GUI_AddArchive extends javax.swing.JFrame implements PropertyChangeListener {

    /**
     * Creates new form GUI_AddArchive
     */
    Filtro filtro;
    GUI_Logminer logminer;
    private String regla;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        
        @Override
        public Void doInBackground() {
            logminer.getStartButton().setEnabled(false);
            logminer.getStatusLabel().setText("Loading..");
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //Initialize progress property.
            this.
            setProgress(0);/////////////////////////////////////
            ArrayList<String> archive = new ArrayList();
            for (int i = 0; i < archivesTable.getRowCount(); i++) {

                archive.add((String) archivesTable.getModel().getValueAt(i, 1));
            }
            filtro.setArchives(archive);

            setProgress(10);///////////////////////////////////////

            String scriptBuild = filtro.crearLogminerScript();
            String query = filtro.crearLogminerQuery();

            setProgress(20);//////////////////////////////////////

            Control control = Control.getInstance();
            ServicioMenu servicio = control.getServicioMenu();
            
            //Logs
            Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.AUDIT,query);
            control.insertLog(log);
            control.saveLogs();

            setProgress(40);/////////////////////////////////////

            ArrayList<String> lista = null;
            try {
                servicio.startLogminer(scriptBuild);
                setProgress(70);/////////////////////////////////////
                if (regla == null) {
                    lista = servicio.getLogminerResult(query);
                     setProgress(80);/////////////////////////////////////
                } else {
                    //JOptionPane.showMessageDialog(this,servicio.getLogminerComp(query,control.searchRule(regla)));
                    lista = servicio.getLogminerComp(query, control.searchRule(regla));
                     setProgress(85);/////////////////////////////////////
                }
                setProgress(90);/////////////////////////////////////
            } catch (GlobalException | NoDataException ex) {
                Logger.getLogger(GUI_AddArchive.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (lista != null) {
                cargarTabla(lista);
            }
            logminer.getRowSelectedLabel().setText(logminer.getLogminerTable().getRowCount() + " rows selected");
//            GUI_logminerscript s = new GUI_logminerscript(scriptBuild + "\n" + query);
//            s.setVisible(true);
            setProgress(100);
            logminer.getStatusLabel().setText("Done");
            setProgress(0);
            return null;
        }

        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            logminer.getStartButton().setEnabled(true);
            setCursor(null); //turn off the wait cursor
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException ignore) {}
//            this.setProgress(0);
        }
    }

    public GUI_AddArchive(Filtro filtro, GUI_Logminer t, String rr) {
        initComponents();
        this.filtro = filtro;
        centreWindow(this);
        this.logminer = t;
        this.regla = rr;
        this.archivesTable.getTableHeader().setReorderingAllowed(false);

    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            logminer.getProgressBar().setValue(progress);
        }
    }

    public static void centreWindow(Window frame) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);
    }

    public void cargarTabla(ArrayList<String> lista) {
        for (int i = 0; i < ((DefaultTableModel) logminer.getLogminerTable().getModel()).getRowCount();) {
            ((DefaultTableModel) logminer.getLogminerTable().getModel()).removeRow(i);
        }

        for (int i = 0; i < lista.size(); i += 6) {
            ((DefaultTableModel) logminer.getLogminerTable().getModel()).addRow(new Object[]{lista.get(i), lista.get(i + 1), lista.get(i + 2), lista.get(i + 3), lista.get(i + 4), lista.get(i + 5)});
            /*for(int j = 0; j < 6;j++){
                //((DefaultTableModel) logminer.getLogminerTable().getModel()).getValueAt(i, j).;
                
            }*/
        }
    }

    public String getRegla() {
        return regla;
    }

    public void setRegla(String regla) {
        this.regla = regla;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        archivesTable = new javax.swing.JTable();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        aceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add Archive Log File");

        archivesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Path"
            }
        ));
        jScrollPane1.setViewportView(archivesTable);

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        removeButton.setText("Remove");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        aceptButton.setText("Start");
        aceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 477, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(removeButton, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                    .addComponent(aceptButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeButton)
                        .addGap(18, 18, 18)
                        .addComponent(aceptButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        JFileChooser fc = new JFileChooser("C:\\oraclexe\\app\\oracle\\flash_recovery_area\\XE\\ARCHIVELOG");
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("ARC", "arc");
        fc.setFileFilter(filter);
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            ((DefaultTableModel) archivesTable.getModel()).addRow(new Object[]{fc.getSelectedFile().getName(), fc.getSelectedFile().getAbsolutePath()});
        }
    }//GEN-LAST:event_addButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        int index = archivesTable.getSelectedRow();
        if (index >= 0) {
            ((DefaultTableModel) archivesTable.getModel()).removeRow(index);

        } else {
            JOptionPane.showMessageDialog(this, "Error", "Select a row", JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_removeButtonActionPerformed

    private void aceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptButtonActionPerformed

      
        logminer.clearTable(logminer.getLogminerTable());

        Task task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
        
        this.dispose();
    }//GEN-LAST:event_aceptButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptButton;
    private javax.swing.JButton addButton;
    private javax.swing.JTable archivesTable;
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton removeButton;
    // End of variables declaration//GEN-END:variables
}
